#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
from spotify import *
import json

app = Flask(__name__)

# 创建Logger
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.INFO)
logger = logging.getLogger()


@app.route('/resource/health', methods=['GET'])
def token():
    return jsonify({'data': '200,deploy again'})


def covertToJson(artist_list):
    result = []
    for artist in artist_list:
        tmp_artist = {}
        #tmp_artist['uri'] = artist.uri
        tmp_artist['id'] = artist.id
        tmp_artist['name'] = artist.name
        tmp_artist['image'] = artist.image
        # 设置所有的album
        tmp_artist['albums'] = convertAlbumAndJson(artist.albums)
        # 设置所有的singles
        tmp_artist['singles'] = convertAlbumAndJson(artist.singles)
        result.append(tmp_artist)
    return result


def convertAlbumAndJson(albums):
    album_list = []
    for album in albums:
        tmp_album = {}
        tmp_album['name'] = album.name
        #tmp_album['uri'] = album.uri
        tmp_album['id'] = album.id
        tmp_album['cover'] = album.cover
        album_list.append(tmp_album)
        song_list = []
        for song in album.songs:
            tmp_song = {}
            tmp_song['name'] = song.name
            #tmp_song['uri'] = song.uri
            tmp_song['id'] = song.id
            song_list.append(tmp_song)
        tmp_album['songs'] = song_list
    return album_list


@app.route('/crawl-artist-by-name', methods=['Post'])
def crawl_artist():
    data = request.json
    logger.info('start fetch [[%s]] singles and EPs task!', data['names'])
    # 所有的歌曲
    artist_list = []
    # 首先需要获取token
    token = get_access_token()
    logger.info(token)
    # 进行遍历
    for artist in data['names']:
        logger.info("artiest -> %s ", artist)
        # 查询所有与name有关联的歌手，选取其中一个就行
        all_artists = query(artist, token)
        if not all_artists:
            continue
        # 选取其中一个就行
        tmp_artist = all_artists[0]
        logger.info("relation artist -> %s", tmp_artist.name)
        artist_list.append(tmp_artist)
        name = tmp_artist.name
        id = tmp_artist.id
        uri = tmp_artist.uri
        # 开始查询歌手的专辑列表
        albums_singles = homepage(uri, token)
        for tmp in albums_singles:
            logger.info("albums_singles albums_singles -> %s", tmp)
        # 专辑
        albums = albums_singles[0]
        tmp_artist.albums = albums
        # 单曲
        singles = albums_singles[1]
        tmp_artist.singles = singles
        for album in albums:
            logger.info("album name -> %s", album.name)
            song_list = album_info(album.uri, token)
            album.songs = song_list
        for single in singles:
            logger.info("singles name -> %s", single.name)
            song_list = album_info(single.uri, token)
            single.songs = song_list
    result = covertToJson(artist_list)
    return jsonify({'data': result})


# 启动程序
if __name__ == '__main__':
    app.run(port=8080, debug=True, host="0.0.0.0")
